#include <stdio.h>

int main(int argc, char *argv[])
{
    FILE *fp, *fout;
    int cs;
    int ip;
    long pos;
    char buf[512] = {0};

    if (argc != 3)
    {
        printf("parameter is invalid\n");
        printf("parameter: <exefile> <binfile>\n");
        return -1;
    }
    fp = fopen(argv[1], "rb");
    if (fp == NULL)
    {
        printf("Open %s error\n", argv[1]);
        return -2;
    }
    fseek(fp, 0x12, SEEK_SET);
    fread(&cs, sizeof(int), 1, fp);
    fread(&ip, sizeof(int), 1, fp);
    printf("Current Entry is CS:IP = %04X:%04X\n", cs, ip);
    fout = fopen(argv[2], "wb");
    if (fout == NULL)
    {
        printf("Open %s error\n", argv[2]);
        return -3;
    }
    printf("Copying...\n");
    pos = ip + 512;
    fseek(fp, pos, SEEK_SET);
    pos = fread(buf, 1, 512, fp);
    printf("Data size %d bytes\n", pos);
    if (pos > 510)
    {
        printf("Warning: size is too big for bootsector\n");
    }
    buf[510] = 0x55;
    buf[511] = 0xAA;
    fwrite(buf, 1, 512, fout);
    printf("\n");
    fclose(fp);
    fclose(fout);
    printf("write success\n");

    return 0;
}